package com.lai.laiojcodesandbox.pool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Docker容器池
 */
@Slf4j
@Component
public class DockerContainerPool {
    /** 超时等待最长时间 */
    public static final Integer LIMIT_TIME = 1;

    /** 容器池队列大小 */
    public static final Integer QUEUE_SIZE = 1;

    /** 容器池队列 */
    private final LinkedBlockingQueue<String> containerPool;

    private DockerContainerPool(){
        this.containerPool = new LinkedBlockingQueue<>(QUEUE_SIZE);
    }

    public DockerContainerPool(int size,List<String> array){
        this.containerPool = new LinkedBlockingQueue<>(size);
        initializeContainers(array);
    }

    /**
     * 容器队列初始化
     * @param array 容器id集合
     */
    public void initializeContainers(List<String> array){
        for (String s : array) {
            containerPool.offer(s);
        }
    }

    /**
     * 获取空闲容器
     * @return 容器id
     */
    public String acquireContainer()  {
        try{
            // 从队列中获取一个容器 ID，若没有则等待
            return containerPool.poll(LIMIT_TIME, TimeUnit.SECONDS);
        }catch (InterruptedException e){
            log.error("容器池获取容器失败，原因：{}",e.getMessage());
            return null;
        }
    }

    /**
     * 容器归还
     * @param containerId 容器id
     */
    public void releaseContainer(String containerId) {
        // 将容器 ID 放回池中
        containerPool.offer(containerId);
    }

    @Override
    public String toString() {
        return Arrays.toString(containerPool.toArray());
    }

    public String[] toArray(){
        return containerPool.toArray(new String[0]);
    }
}
